package com.imooc.socialecom.service.impl;

import com.imooc.socialecom.pojo.MessageInfo;
import com.imooc.socialecom.service.MessageService;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private Connection hbaseConnection;

    @Override
    public MessageInfo postMessage(MessageInfo messageInfo) throws IOException {

        messageInfo.setId(UUID.randomUUID().toString().replace("-", ""));
        messageInfo.setLikeCount(0);
        messageInfo.setRemarkCount(0);

        Table table = null;
        table = hbaseConnection.getTable(TableName.valueOf("Message"));

        Put line = new Put(messageInfo.getId().getBytes());
        line.addColumn("base".getBytes(), "content".getBytes(), messageInfo.getContent().getBytes());
        line.addColumn("base".getBytes(), "userId".getBytes(), messageInfo.getUserId().toString().getBytes());
        line.addColumn("base".getBytes(), "itemId".getBytes(), messageInfo.getItemId().toString().getBytes());
        line.addColumn("base".getBytes(), "shopId".getBytes(), messageInfo.getShopId().toString().getBytes());

        line.addColumn("count".getBytes(), "likeCount".getBytes(), messageInfo.getLikeCount().toString().getBytes());
        line.addColumn("count".getBytes(), "remarkCount".getBytes(), messageInfo.getRemarkCount().toString().getBytes());


        table.put(line);

        return messageInfo;
    }

    @Override
    public MessageInfo getMessage(String id) throws IOException {

        Table table = null;
        table = hbaseConnection.getTable(TableName.valueOf("Message"));

        Result result = table.get(new Get(id.getBytes()));
        if (result.getRow() == null) {
            return null;
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setId(new String(result.getRow()));
        messageInfo.setContent(new String(result.getValue("base".getBytes(), "content".getBytes())));
        messageInfo.setUserId(new Integer(new String(result.getValue("base".getBytes(), "userId".getBytes()))));
        messageInfo.setItemId(new Integer(new String(result.getValue("base".getBytes(), "itemId".getBytes()))));
        messageInfo.setShopId(new Integer(new String(result.getValue("base".getBytes(), "shopId".getBytes()))));

        messageInfo.setLikeCount(new Integer(new String(result.getValue("count".getBytes(), "likeCount".getBytes()))));
        messageInfo.setRemarkCount(new Integer(new String(result.getValue("count".getBytes(), "remarkCount".getBytes()))));
        return messageInfo;
    }
}
